/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.dp.view;

import com.dp.dto.BaseDTO;
import com.dp.utils.ReflectionUtils;
import java.awt.Component;
import java.lang.reflect.Method;
import javax.swing.JComboBox;
import javax.swing.JSpinner;
import javax.swing.JTextField;

/**
 *
 * @author hisik
 */
public class AbstractPage<DTO extends BaseDTO> extends javax.swing.JPanel implements IBasePage<DTO>{
    
    protected DTO dto;

    public AbstractPage() {
        
        dto = (DTO) ReflectionUtils.createDTOInstance(this.getClass().getName().replace("view", "dto") + "DTO"); // this is a standard DTO name. this must be
        
    }

    public DTO getDto() {
        return dto;
    }
    
    public static AbstractPage getInstance(Class clazz) {
        
        if(clazz.equals(BookAdd.class))
            return new BookAdd();
        if(clazz.equals(ArticleAdd.class))
            return new ArticleAdd();
        if(clazz.equals(BookList.class))
            return new BookList();
        if(clazz.equals(ArticleList.class))
            return new ArticleList();
        
        return null;
    }
    
    protected void bindDTO() {
        
        for(Component comp : getComponents()) {
            String setter = comp.getName();
            if(setter == null) continue;
            
            setter = "set" + setter.substring(0, 1).toUpperCase() + setter.substring(1);
            
            if (setter.substring(3, 4).charAt(0) == 'İ') {
                setter = setter.substring(0,3) + "I" + setter.substring(4);
            }

            try {
                if(comp instanceof JTextField) {
                    JTextField jtf = (JTextField)comp;

                    Method method = dto.getClass().getMethod(setter , new Class[]{String.class});
                    method.invoke(dto, jtf.getText());
                }
                else if(comp instanceof JComboBox) {
                    JComboBox jcb = (JComboBox)comp;

                    Method method = dto.getClass().getMethod(setter , new Class[]{String.class});
                    method.invoke(dto, jcb.getSelectedItem());
                }
                else if(comp instanceof JSpinner) {
                    JSpinner jsp = (JSpinner)comp;

                    Method method = dto.getClass().getMethod(setter , new Class[]{int.class});
                    method.invoke(dto, jsp.getValue());
                }
            }
            catch(Exception ex) {
                System.out.println(ex.getMessage());
            }
        }
    }

}
